package com.kuaidi100.sdk.utils;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.*;
import java.util.*;

public class JsonUtils {

	private static final ObjectMapper objectMapper = new ObjectMapper();

	public static <T> List<T> parseArray(String json, Class<T> clazz) {
		return JSONArray.parseArray(json,clazz);
	}
	public static <T> T parseObject(String json, Class<T> clazz) {
		return JSONObject.parseObject(json,clazz);
	}
	/**
	 * 反序列化 JSON 转对象集合
	 * @param json
	 * @param clazz
	 * @param <T>
	 * @return
	 */
	public static <T> List<T> fromJsonToListJackson(String json, Class<T> clazz) {
		try {
			objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
			List<T> list = objectMapper.readValue(json, new TypeReference<List<T>>() {});
			return new ArrayList<>(list);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}
	/**
	 * 反序列化 JSON 转对象
	 * @param json
	 * @param clazz
	 * @param <T>
	 * @return
	 */
	public static <T> T fromJson(String json, Class<T> clazz) {
		try {
			objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
			return objectMapper.readValue(json, clazz);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}

	public static boolean isNested(Object jsonObj){
		return JSON.isValidObject(jsonObj.toString());
	}

	public static Map<String,Object> toMap(String jsonStr) {
		JSONObject jsonObject = JSON.parseObject(jsonStr);
		HashMap<String, Object> map = new HashMap<>();
		Set<Map.Entry<String, Object>> entries = jsonObject.entrySet();
		for (Map.Entry<String, Object> entry : entries) {
			map.put(entry.getKey(),entry.getValue());
		}
		return map;
	}
	/**
	 * 读取json文件，返回json串
	 *
	 * @param fileName
	 * @return
	 */
	public static String readJsonFile(String fileName) {
		String jsonStr = "";
		try {
			File jsonFile = new File(fileName);
			FileReader fileReader = new FileReader(jsonFile);

			Reader reader = new InputStreamReader(new FileInputStream(jsonFile), "utf-8");
			int ch = 0;
			StringBuffer sb = new StringBuffer();
			while ((ch = reader.read()) != -1) {
				sb.append((char) ch);
			}
			fileReader.close();
			reader.close();
			jsonStr = sb.toString();
			return jsonStr;
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		}
	}

	public static String toJson(Object object) {
		return JSON.toJSONString(object);
	}
}
